package com.bachelor.community.controller;

import cn.hutool.core.util.ObjectUtil;
import com.bachelor.community.annotation.UnInterception;
import com.bachelor.community.model.entity.QuestionTagRelation;
import com.bachelor.community.model.entity.Tag;
import com.bachelor.community.service.intf.QuestionTagService;
import com.bachelor.community.service.intf.TagService;
import com.bachelor.community.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/tags")
public class TagController {
    private final TagService tagService;
    private final QuestionTagService questionTagService;

    @Autowired
    public TagController(TagService tagService, QuestionTagService questionTagService) {
        this.tagService = tagService;
        this.questionTagService = questionTagService;
    }

    @GetMapping
    @UnInterception
    public Result listTags(@RequestParam(value = "keyword", required = false) String keyword) {
        if (ObjectUtil.isEmpty(keyword)) {
            return Result.succeed("200", tagService.list());
        } else {
            return Result.succeed("200", tagService.searchTags(keyword));
        }
    }

    @GetMapping("/hot")
    @UnInterception
    public Result listHotTags() {
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("count", 0);
        return Result.succeed("200", tagService.list(queryWrapper));
    }

    @PostMapping
    public Result insertTag(@RequestBody Tag tag) {
        return Result.succeed("201", tagService.save(tag));
    }

    @PatchMapping("{tagId}")
    public Result partialUpdateTag(@PathVariable Integer tagId, @RequestBody Tag tagDTO) {
        Tag tag = tagService.getById(tagId);
        tag.setName(tagDTO.getName());
        tag.setDescription(tagDTO.getDescription());
        tagService.updateById(tag);
        return Result.succeed("200", tag);
    }

    @DeleteMapping("{tagId}")
    public Result removeTag(@PathVariable Integer tagId) {
        QueryWrapper<QuestionTagRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag_id", tagId);
        questionTagService.remove(queryWrapper);
        return Result.succeed("204", tagService.removeById(tagId));
    }
}
